﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Management.Automation.Runspaces;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

/*
Install-Package System.Management.Automation
Install-Package Microsoft.PowerShell.5.ReferenceAssemblies -Version 1.1.0

 */
public partial class Start_VM_Name_Win2020 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        RunspaceConfiguration rconfig = RunspaceConfiguration.Create();
        PSSnapInException Pwarn = new PSSnapInException();

        Runspace runspace = RunspaceFactory.CreateRunspace();
        string test = "Import-Module VirtualMachineManager\r\n";
        runspace = RunspaceFactory.CreateRunspace(rconfig);
        runspace.Open();
        Pipeline pipeline = runspace.CreatePipeline();
        pipeline.Commands.AddScript(test);

        var results = pipeline.Invoke();

        using (Pipeline pipe = runspace.CreatePipeline())
        {
            //Start-VM -name XXXXX
            Command cmd = new Command("Start-VM");
            //Command cmd = new Command("help");
            string currentPageFileName = new FileInfo(this.Request.Url.LocalPath).Name;
            string sVMName = currentPageFileName.Substring(currentPageFileName.LastIndexOf("_") + 1, currentPageFileName.LastIndexOf(".aspx") - currentPageFileName.LastIndexOf("_") - 1);
            cmd.Parameters.Add("Name", sVMName);
            pipe.Commands.Add(cmd);
            var result = pipe.Invoke();
            Label1.Text = sVMName + "  " + result.Count;
        }
    }
}